package com.chaodev.base.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description:    日志控制类
* @Author:         xy
* @CreateDate:     2019/8/13 15:15
* @UpdateUser:     xy
* @UpdateDate:     2019/8/13 15:15
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
@RestController
@RequestMapping(value="/log")
@Api(value = "日志管理")
public class LogController {

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;


    /**
    * @Description:    访问菜单日志添加
    * @Author:         xy
    * @CreateDate:     2019/8/13 15:41
    * @UpdateUser:     xy
    * @UpdateDate:     2019/8/13 15:41
    * @UpdateRemark:   修改内容
    * @Version:        1.0
    */
    @RequestMapping(value = "/AddMenuLog", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "访问菜单日志新增")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result AddMenuLog(@RequestBody @ApiParam(value = "菜单信息") Menu menu, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            boolean flag = logService.addMenuLog(menu, userInfo, request);
            if (flag == true) {
                result.setCode(0);
                result.setMsg("新增成功");
            } else {
                result.setCode(-1);
                result.setMsg("新增失败");
            }
            logService.logAdd(menu.toString(), "访问菜单日志新增", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(menu.toString(), "访问菜单日志新增", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @RequestMapping(value = "/listLoginLog", method = RequestMethod.POST)
    @ApiOperation(value = "获取用户登录日志")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result listLoginLog(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            if (null == dataPage.getPage()) {
                dataPage.setPage(1);
            }
            if (null == dataPage.getRows()) {
                dataPage.setRows(20);
            }
            if(!org.springframework.util.StringUtils.hasText(dataPage.getSort())){
                dataPage.setSort(" LOG_TIME ");
            }
            if(!org.springframework.util.StringUtils.hasText(dataPage.getOrder())){
                dataPage.setSort(" DESC ");
            }
            if(!StringUtils.hasText(dataPage.getDepartId()))
            {
                dataPage.setDepartId(userInfo.getDepartId());
            }
            PageInfo<LogUserLogin> pageInfo=logService.listLoginLog(dataPage);
            result.setCode(0);
            Map<String, Object> map = new HashMap<>(2);
            map.put("total", pageInfo.getTotal());
            map.put("rows", pageInfo.getList());
            result.setData(map);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取用户登录日志", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取用户登录日志", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @PostMapping(value = "/listUserLog")
    @ApiOperation(value = "获取用户操作日志")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result listUserLog(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            if (null == dataPage.getPage()) {
                dataPage.setPage(1);
            }
            if (null == dataPage.getRows()) {
                dataPage.setRows(20);
            }
            if(!org.springframework.util.StringUtils.hasText(dataPage.getSort())){
                dataPage.setSort(" LOG_REQUEST_TIME ");
            }
            if(!org.springframework.util.StringUtils.hasText(dataPage.getOrder())){
                dataPage.setSort(" DESC ");
            }
            if(!StringUtils.hasText(dataPage.getDepartId()))
            {
                dataPage.setDepartId(userInfo.getDepartId());
            }
            PageInfo<LogOperation> pageInfo=logService.listUserLog(dataPage);
            result.setCode(0);
            Map<String, Object> map = new HashMap<>(2);
            map.put("total", pageInfo.getTotal());
            map.put("rows", pageInfo.getList());
            result.setData(map);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取用户操作日志", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取用户操作日志", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @PostMapping(value = "/getMenuChartsData")
    @ApiOperation(value = "获取菜单统计图表数据")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getMenuChartsData(@RequestBody Map<String,Object> map, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            List<Map<String,Object>> listData=logService.getMenuChartsData(map);
            List<List<String>> resultList=new ArrayList<>();
            if(!listData.isEmpty()){
                //转换数据
                List<String> nameList=new ArrayList<>();
                List<String> numList=new ArrayList<>();
                for(Map<String,Object> item:listData){
                    nameList.add(item.get("name").toString());
                    numList.add(item.get("num").toString());
                }
                resultList.add(nameList);
                resultList.add(numList);
            }
            result.setCode(0);
            result.setData(resultList);
            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(JSONObject.toJSONString(map), "获取菜单统计图表数据", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(JSONObject.toJSONString(map), "获取菜单统计图表数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @PostMapping(value = "/getUserChartsData")
    @ApiOperation(value = "获取用户统计图表数据")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getUserChartsData(@RequestBody Map<String,Object> map, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            List<Map<String,Object>> listData=logService.getUserChartsData(map);
            List<List<String>> resultList=new ArrayList<>();
            if(!listData.isEmpty()){
                //转换数据
                List<String> nameList=new ArrayList<>();
                List<String> numList=new ArrayList<>();
                for(Map<String,Object> item:listData){
                    nameList.add(item.get("name").toString());
                    numList.add(item.get("num").toString());
                }
                resultList.add(nameList);
                resultList.add(numList);
            }
            result.setCode(0);
            result.setData(resultList);
            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(JSONObject.toJSONString(map), "获取用户统计图表数据", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(JSONObject.toJSONString(map), "获取用户统计图表数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
    @PostMapping(value = "/getErrorChartsData")
    @ApiOperation(value = "获取正常与错误请求统计图表数据")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getErrorChartsData(@RequestBody Map<String,Object> map, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            List<Map<String,Object>> listData=logService.getErrorChartsData(map);
//            List<List<String>> resultList=new ArrayList<>();
//            if(!listData.isEmpty()){
//                //转换数据
//                List<String> nameList=new ArrayList<>();
//                List<String> numList=new ArrayList<>();
//                for(Map<String,Object> item:listData){
//                    nameList.add(item.get("name").toString());
//                    numList.add(item.get("num").toString());
//                }
//                resultList.add(nameList);
//                resultList.add(numList);
//            }
            result.setCode(0);
            result.setData(listData);
            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(JSONObject.toJSONString(map), "获取正常与错误请求统计图表数据", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(JSONObject.toJSONString(map), "获取正常与错误请求统计图表数据", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/listErrorLog")
    @ApiOperation(value = "获取错误日志列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result listErrorLog(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token,redisDao);
            if (null == dataPage.getPage()) {
                dataPage.setPage(1);
            }
            if (null == dataPage.getRows()) {
                dataPage.setRows(20);
            }
            PageInfo<ErrorLog> pageInfo=logService.listErrorLog(dataPage);
            result.setCode(0);
            Map<String, Object> map = new HashMap<>(2);
            map.put("total", pageInfo.getTotal());
            map.put("rows", pageInfo.getList());
            result.setData(map);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取错误日志列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取错误日志列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
   /**
   * @Description:    异常处理    为了方便对异常的统一管理使用ControllerAdvice注解对异常进行统一的处理
   * @Author:         xy
   * @CreateDate:     2019/8/16 16:17
   * @UpdateUser:     xy
   * @UpdateDate:     2019/8/16 16:17
   * @UpdateRemark:   修改内容
   * @Version:        1.0
   */
    @ControllerAdvice
    @ResponseBody
    public class ExceptionController {
        private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
        //异常
        @ExceptionHandler(Exception.class)
        public void ExceptionHandler(HttpServletRequest request, Exception ex) {
            Throwable throwable=ex.getCause();
            if(throwable==null)
            {
                String s=ex.toString();
                logService.addErrorLog(request, s, "");
            }
            else {
                String s = ex.getCause().toString();
                //System.out.println(s);
                logService.addErrorLog(request, s, "");
            }
        }
    }

}
